package com.lemobar.pay.service.impl.alipay;

import com.google.gson.FieldNamingPolicy;
import com.google.gson.GsonBuilder;
import com.lemobar.pay.constants.AliPayConstants;
import com.lemobar.pay.model.PayRequest;
import com.lemobar.pay.model.PayResponse;
import com.lemobar.pay.model.alipay.AliPayApi;
import com.lemobar.pay.model.alipay.request.AliPayTradeCreateRequest;
import com.lemobar.pay.model.alipay.request.AliPayTradeWapPayRequest;
import com.lemobar.pay.utils.JsonUtil;
import com.lemobar.pay.utils.MapUtil;
import com.lemobar.pay.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import java.io.IOException;
import java.time.LocalDateTime;

/**
 * 支付宝 WAP 支付
 *
 */
@Slf4j
public class AlipayWapServiceImpl extends AliPayServiceImpl {

	private Retrofit retrofit = new Retrofit.Builder()
			.baseUrl(AliPayConstants.ALIPAY_GATEWAY_OPEN)
			.addConverterFactory(GsonConverterFactory.create(
					new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create()
			))
			.client(new OkHttpClient.Builder()
					.addInterceptor((new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)))
					.build()
			).build();


	@Override
	public PayResponse pay(PayRequest request) {
		AliPayTradeWapPayRequest aliPayTradeWapPayRequest = new AliPayTradeWapPayRequest();
		aliPayTradeWapPayRequest.setAppId(aliPayConfig.getAppId());
		aliPayTradeWapPayRequest.setTimestamp(LocalDateTime.now().format(formatter));
		aliPayTradeWapPayRequest.setNotifyUrl(StringUtil.isEmpty(request.getNotifyUrl()) ? aliPayConfig.getNotifyUrl() : request.getNotifyUrl());

		AliPayTradeCreateRequest.BizContent bizContent = new AliPayTradeCreateRequest.BizContent();
		bizContent.setOutTradeNo(request.getOrderId());
		bizContent.setTotalAmount(request.getOrderAmount());
		bizContent.setSubject(request.getOrderName());

		bizContent.setBuyerId(request.getOpenid());

		aliPayTradeWapPayRequest.setBizContent(JsonUtil.toJsonWithUnderscores(bizContent).replaceAll("\\s*",""));
		aliPayTradeWapPayRequest.setSign("2"+AliPaySignature.sign(MapUtil.object2MapWithUnderline(aliPayTradeWapPayRequest), aliPayConfig.getPrivateKey()));

		Call<ResponseBody> call = retrofit.create(AliPayApi.class)
				.tradeWapPay((MapUtil.object2MapWithUnderline(aliPayTradeWapPayRequest)));

		Response<ResponseBody> retrofitResponse = null;
		try{
			retrofitResponse = call.execute();
		}catch (IOException e) {
			e.printStackTrace();
		}
		assert retrofitResponse != null;
		if (!retrofitResponse.isSuccessful()) {
			throw new RuntimeException("【支付宝创建订单】网络异常. alipay.trade.wap.pay");
		}
		String body = null;
		try {
			body = retrofitResponse.body().string();
		} catch (IOException e) {
			e.printStackTrace();
		}

		PayResponse payResponse = new PayResponse();
		payResponse.setBody(body);
		return payResponse;
	}
}
